package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.ItemDescMapper;
import com.jt.mapper.ItemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemCat;
import com.jt.pojo.ItemDesc;
import com.jt.vo.ImageVO;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.awt.print.Paper;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Autowired
    private ItemDescMapper itemDescMapper;
@Autowired
private FileService fileService;

    @Override
    @Transactional
    public PageResult getItemList(PageResult pageResult) {
        QueryWrapper<Item> queryWrapper=new QueryWrapper<>();
        boolean flag= StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag,"title", pageResult.getQuery());
        Page<Item> page=new Page<>(pageResult.getPageNum(),pageResult.getPageSize());
        page= itemMapper.selectPage(page,queryWrapper);
        long total=page.getTotal();
        List<Item>rows=page.getRecords();

        return pageResult.setTotal(total).setRows(rows);
    }

    @Override
    @Transactional
    public void updateItemStatus(Item item) {

        itemMapper.updateById(item);
    }

    @Override
    @Transactional
    public void deleteItemById(Integer id) {
        Item item=itemMapper.selectById(id);
        String[] images = item.getImages().split(".");
        for(String imagePath: images){
        fileService.deleteFile(imagePath);
        }
        itemDescMapper.deleteById(id);
        itemMapper.deleteById(id);
    }

    /**
     *  难点: 数据如何回显
     *  1.useGeneratedKeys="true" keyColumn="字段" keyProperty="属性名"
     *  2.MP自动将数据进行回显
     */
    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
        //1.入库商品表
        Item item=itemVO.getItem();
        item.setStatus(true);
        //ID主键自增,入库之后才会有ID,要求Id自动回显!!!
        itemMapper.insert(item);
        //2.商品入库操作
        ItemDesc itemDesc=itemVO.getItemDesc();
        itemDesc.setId(item.getId());
        itemDescMapper.insert(itemDesc);

    }
    /**
     * 请求路径: http://localhost:8091/file/upload
     * 请求类型: post
     * 请求参数:
     * */
}
